<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>79-WebStorage | 小黑博客</title><meta name="keywords" content="JavaScript,JavaScript高级程序设计第四版"><meta name="author" content="BluesYoung-web"><meta name="copyright" content="BluesYoung-web"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="IE用户数据 每个文档最多128K 每个域名最多1M 域名限制同cookie 不会过期，需要手动删除  123456789101112131415&lt;div style&#x3D;&quot;behavior:url(#default#userData)&quot; id&#x3D;&quot;dataStore&quot;&gt;&lt;&#x2F;div&gt;&lt;script&gt;var dataStore &#x3D;">
<meta property="og:type" content="article">
<meta property="og:title" content="79-WebStorage">
<meta property="og:url" content="https://bluesyoung-web.gitee.io/blog/2021-02-06-79-WebStorage.html">
<meta property="og:site_name" content="小黑博客">
<meta property="og:description" content="IE用户数据 每个文档最多128K 每个域名最多1M 域名限制同cookie 不会过期，需要手动删除  123456789101112131415&lt;div style&#x3D;&quot;behavior:url(#default#userData)&quot; id&#x3D;&quot;dataStore&quot;&gt;&lt;&#x2F;div&gt;&lt;script&gt;var dataStore &#x3D;">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://bluesyoung-web.gitee.io/blog/img/hbs.png">
<meta property="article:published_time" content="2021-02-06T06:40:35.000Z">
<meta property="article:modified_time" content="2021-08-29T11:36:10.269Z">
<meta property="article:author" content="BluesYoung-web">
<meta property="article:tag" content="JavaScript">
<meta property="article:tag" content="JavaScript高级程序设计第四版">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://bluesyoung-web.gitee.io/blog/img/hbs.png"><link rel="shortcut icon" href="/blog/img/favicon.png"><link rel="canonical" href="https://bluesyoung-web.gitee.io/blog/2021-02-06-79-WebStorage"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="stylesheet" href="/blog/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/blog/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: {"limitCount":50,"languages":{"author":"作者: BluesYoung-web","link":"链接: ","source":"来源: 小黑博客","info":"著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。"}},
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#121212","position":"top-right"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '79-WebStorage',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: false,
  postUpdate: '2021-08-29 19:36:10'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/blog/css/background.css"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/sviptzk/HexoStaticFile@latest/Hexo/css/custom.min.css"></link><meta name="generator" content="Hexo 5.4.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/blog/img/lufei_siwangningshi.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data is-center"><div class="data-item"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">153</div></a></div><div class="data-item"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">54</div></a></div><div class="data-item"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">48</div></a></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('/blog/img/hbs.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/blog/">小黑博客</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">79-WebStorage</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-02-06T06:40:35.000Z" title="发表于 2021-02-06 14:40:35">2021-02-06</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-08-29T11:36:10.269Z" title="更新于 2021-08-29 19:36:10">2021-08-29</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/">学习笔记</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/JavaScript%E9%AB%98%E7%BA%A7%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/">JavaScript高级程序设计</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/JavaScript%E9%AB%98%E7%BA%A7%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/%E7%AC%AC25%E7%AB%A0%E2%80%94%E2%80%94%E5%AE%A2%E6%88%B7%E7%AB%AF%E5%AD%98%E5%82%A8/">第25章——客户端存储</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">967</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>4分钟</span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="IE用户数据"><a href="#IE用户数据" class="headerlink" title="IE用户数据"></a>IE用户数据</h2><ul>
<li>每个文档最多128K</li>
<li>每个域名最多1M</li>
<li>域名限制同cookie</li>
<li>不会过期，需要手动删除</li>
</ul>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">style</span>=<span class="string">&quot;behavior:url(#default#userData)&quot;</span> <span class="attr">id</span>=<span class="string">&quot;dataStore&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript"><span class="keyword">var</span> dataStore = <span class="built_in">document</span>.querySelector(<span class="string">&#x27;#dataStore&#x27;</span>);</span></span><br><span class="line"><span class="javascript"><span class="comment">// 保存数据</span></span></span><br><span class="line"><span class="javascript">dataStore.setAttribute(<span class="string">&quot;name&quot;</span>, <span class="string">&quot;bluesyoung&quot;</span>);</span></span><br><span class="line"><span class="javascript"><span class="comment">// 将修改存储到数据空间</span></span></span><br><span class="line"><span class="javascript">dataStore.save(<span class="string">&#x27;nameInfo&#x27;</span>);</span></span><br><span class="line"><span class="javascript"><span class="comment">// 加载数据空间</span></span></span><br><span class="line"><span class="javascript">dataStore.load(<span class="string">&#x27;nameInfo&#x27;</span>);</span></span><br><span class="line"><span class="javascript"><span class="comment">// 获取存储的数据</span></span></span><br><span class="line"><span class="javascript">dataStore.getAttribute(<span class="string">&#x27;name&#x27;</span>);</span></span><br><span class="line"><span class="javascript"><span class="comment">// 删除存储的数据</span></span></span><br><span class="line"><span class="javascript">dataStore.removeAttribute(<span class="string">&#x27;name&#x27;</span>);</span></span><br><span class="line"><span class="javascript">dataStore.save(<span class="string">&#x27;nameInfo&#x27;</span>);</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h2 id="Storage"><a href="#Storage" class="headerlink" title="Storage"></a><code>Storage</code></h2><ul>
<li>基类</li>
<li><code>sessionStorage</code></li>
<li><code>localStorage</code></li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">length               <span class="comment">// 返回保存数据项的个数</span></span><br><span class="line">clear()              <span class="comment">// 清空所有存储的数据</span></span><br><span class="line">getItem(key)         <span class="comment">// 读取</span></span><br><span class="line">key(index)           <span class="comment">// 返回对应位置的键值，0基</span></span><br><span class="line">removeItem(key)      <span class="comment">// 删除对应键值对</span></span><br><span class="line">setItem(key, value)  <span class="comment">// 存储</span></span><br></pre></td></tr></table></figure>

<h2 id="sessionStorage"><a href="#sessionStorage" class="headerlink" title="sessionStorage"></a><code>sessionStorage</code></h2><ul>
<li>只存储会话数据，关闭页签就会清空</li>
<li>不受页面刷新的影响，浏览器崩溃并重启后恢复</li>
<li><strong>与服务器会话紧密相关，允许本地文件时不能使用</strong></li>
<li>存储写入时都使用了<strong>同步阻塞</strong>方式</li>
<li>基本上每个源 <code>5M</code></li>
</ul>
<h2 id="localStorage"><a href="#localStorage" class="headerlink" title="localStorage"></a><code>localStorage</code></h2><ul>
<li><p>客户端<strong>持久</strong>存储数据的机制</p>
</li>
<li><p>要访问同一个 <code>localStorage</code> 对象，页面必须来自同一个域（子域不可以）、在相同的端口上使用相同的协议</p>
</li>
</ul>
<h2 id="存储事件"><a href="#存储事件" class="headerlink" title="存储事件"></a>存储事件</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">window</span>.addEventListener(<span class="string">&#x27;storage&#x27;</span>, <span class="function">(<span class="params">&#123; domain, key, newVal, oldVal &#125;</span>) =&gt;</span> &#123;</span><br><span class="line">  domain; <span class="comment">// 变化对应的域</span></span><br><span class="line">  key;    <span class="comment">// 变化相关的键</span></span><br><span class="line">  newVal; <span class="comment">// 被设置的新值，删除则为 null</span></span><br><span class="line">  oldVal; <span class="comment">// 键变化之前的值</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<h2 id="IndexedDB"><a href="#IndexedDB" class="headerlink" title="IndexedDB"></a><code>IndexedDB</code></h2><ul>
<li>浏览器中存储结构化数据的一个方案</li>
<li>用于替代目前已经废弃的 <code>Web SQL DataBase API</code></li>
<li>设计几乎完全是异步的，需要添加 <code>onerror\onsuccess</code> 事件处理程序</li>
<li>在一个公共命名空间下的一组对象存储，<code>NoSQL</code> 风格</li>
<li>版本号会被转换为 <code>unsigned long long</code>，要使用整数</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> db, request, version = <span class="number">1</span>;</span><br><span class="line">request = indexedDB.open(<span class="string">&quot;admin&quot;</span>, version);</span><br><span class="line">request.onerror = <span class="function">(<span class="params">event</span>) =&gt;</span> alert(<span class="string">`Failed to open: <span class="subst">$&#123;event.target.errorCode&#125;</span>`</span>);</span><br><span class="line">request.onsuccess = <span class="function">(<span class="params">event</span>) =&gt;</span> &#123;</span><br><span class="line"> 		db = event.target.result;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h2 id="对象存储"><a href="#对象存储" class="headerlink" title="对象存储"></a>对象存储</h2><ul>
<li><code>open()</code> 操作会创建一个新数据库，然后触发 <code>upgradeneeded</code> 事件</li>
<li>可以在这个事件处理程序中创建/更新数据库模式</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">request.onupgradeneeded = <span class="function">(<span class="params">event</span>) =&gt;</span> &#123;</span><br><span class="line">   <span class="keyword">const</span> db = event.target.result;</span><br><span class="line">   <span class="comment">// 如果存在则删除当前 objectStore。测试的时候可以这样做</span></span><br><span class="line">   <span class="comment">// 但这样会在每次执行事件处理程序时删除已有数据</span></span><br><span class="line">   <span class="keyword">if</span> (db.objectStoreNames.contains(<span class="string">&quot;users&quot;</span>)) &#123;</span><br><span class="line">      db.deleteObjectStore(<span class="string">&quot;users&quot;</span>);</span><br><span class="line">   &#125;</span><br><span class="line">   db.createObjectStore(<span class="string">&quot;users&quot;</span>, &#123; <span class="attr">keyPath</span>: <span class="string">&quot;username&quot;</span> &#125;);</span><br><span class="line">&#125;; </span><br></pre></td></tr></table></figure>

<h2 id="事务"><a href="#事务" class="headerlink" title="事务"></a>事务</h2><ul>
<li>任何时候，想要读取或修改数据都要通过事务把所有修改操作组织起来</li>
<li>如果不指定参数，则数据库中所有的对象存储<strong>只有读取权限</strong></li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> transaction = db.transaction(<span class="string">&quot;users&quot;</span>);</span><br><span class="line"><span class="keyword">let</span> transaction = db.transaction([<span class="string">&quot;users&quot;</span>, <span class="string">&quot;anotherStore&quot;</span>]); </span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 访问模式：</span></span><br><span class="line"><span class="comment"> * readonly</span></span><br><span class="line"><span class="comment"> * readwrite</span></span><br><span class="line"><span class="comment"> * versionchange</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">let</span> transaction = db.transaction(<span class="string">&quot;users&quot;</span>, <span class="string">&quot;readwrite&quot;</span>); </span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * add() 添加对象</span></span><br><span class="line"><span class="comment"> * put() 更新对象</span></span><br><span class="line"><span class="comment"> * delete() 删除对象</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> transaction = db.transaction(<span class="string">&quot;users&quot;</span>);</span><br><span class="line"><span class="keyword">const</span> store = transaction.objectStore(<span class="string">&quot;users&quot;</span>);</span><br><span class="line"><span class="keyword">const</span> request = store.get(<span class="string">&quot;007&quot;</span>);</span><br><span class="line">request.onerror = <span class="function">(<span class="params">event</span>) =&gt;</span> alert(<span class="string">&quot;Did not get the object!&quot;</span>);</span><br><span class="line">request.onsuccess = <span class="function">(<span class="params">event</span>) =&gt;</span> alert(event.target.result.firstName);</span><br></pre></td></tr></table></figure>

<h3 id="插入对象"><a href="#插入对象" class="headerlink" title="插入对象"></a>插入对象</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// users 是一个用户数据的数组</span></span><br><span class="line"><span class="keyword">let</span> request, requests = [];</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">let</span> user <span class="keyword">of</span> users) &#123;</span><br><span class="line">   request = store.add(user);</span><br><span class="line">   request.onerror = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">   <span class="comment">// 处理错误</span></span><br><span class="line">   &#125;;</span><br><span class="line">   request.onsuccess = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">   <span class="comment">// 处理成功</span></span><br><span class="line">   &#125;;</span><br><span class="line">   requests.push(request);</span><br><span class="line">&#125; </span><br></pre></td></tr></table></figure>

<h3 id="通过游标查询"><a href="#通过游标查询" class="headerlink" title="通过游标查询"></a>通过游标查询</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> transaction = db.transaction(<span class="string">&quot;users&quot;</span>);</span><br><span class="line"><span class="keyword">const</span> store = transaction.objectStore(<span class="string">&quot;users&quot;</span>);</span><br><span class="line"><span class="comment">// 创建游标</span></span><br><span class="line"><span class="keyword">const</span> request = store.openCursor();</span><br><span class="line">request.onsuccess = <span class="function">(<span class="params">event</span>) =&gt;</span> &#123;</span><br><span class="line"> <span class="keyword">const</span> cursor = event.target.result;</span><br><span class="line"> <span class="keyword">let</span> value, updateRequest;</span><br><span class="line"> <span class="keyword">if</span> (cursor) &#123; <span class="comment">// 永远要检查</span></span><br><span class="line">   <span class="keyword">if</span> (cursor.key == <span class="string">&quot;foo&quot;</span>) &#123;</span><br><span class="line">     value = cursor.value; <span class="comment">// 取得当前对象</span></span><br><span class="line">     value.password = <span class="string">&quot;magic!&quot;</span>; <span class="comment">// 更新密码</span></span><br><span class="line">     updateRequest = cursor.update(value); <span class="comment">// 请求保存更新后的对象</span></span><br><span class="line">     updateRequest.onsuccess = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">     <span class="comment">// 处理成功</span></span><br><span class="line">     &#125;;</span><br><span class="line">     updateRequest.onerror = <span class="function">() =&gt;</span> &#123;</span><br><span class="line">     <span class="comment">// 处理错误</span></span><br><span class="line">     &#125;;</span><br><span class="line">   &#125;</span><br><span class="line"> &#125;</span><br><span class="line">&#125;; </span><br></pre></td></tr></table></figure>

<ul>
<li>…</li>
</ul>
<h2 id="限制"><a href="#限制" class="headerlink" title="限制"></a>限制</h2><ul>
<li>不能跨域</li>
<li><code>Firefox</code> 每个域 <code>50M</code>，移动版 <code>5M</code></li>
<li><code>Chrome</code> 每个域 <code>5M</code></li>
<li>空间超限制会请求用户许可</li>
<li><code>Firefox</code> 本地文件不能访问</li>
</ul>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">BluesYoung-web</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://bluesyoung-web.gitee.io/blog/2021-02-06-79-WebStorage.html">https://bluesyoung-web.gitee.io/blog/2021-02-06-79-WebStorage.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://BluesYoung-web.gitee.io/blog" target="_blank">小黑博客</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/blog/tags/JavaScript/">JavaScript</a><a class="post-meta__tags" href="/blog/tags/JavaScript%E9%AB%98%E7%BA%A7%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1%E7%AC%AC%E5%9B%9B%E7%89%88/">JavaScript高级程序设计第四版</a></div><div class="post_share"></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/blog/img/wx.png" target="_blank"><img class="post-qr-code-img" src="/blog/img/wx.png" alt="微信"/></a><div class="post-qr-code-desc">微信</div></li><li class="reward-item"><a href="/blog/img/zfb.jpg" target="_blank"><img class="post-qr-code-img" src="/blog/img/zfb.jpg" alt="支付宝"/></a><div class="post-qr-code-desc">支付宝</div></li></ul></div></div><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/blog/2020-12-28-01-历史回顾.html" title="01-历史回顾"><img class="cover" src="/blog/img/hbs.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">01-历史回顾</div></div></a></div><div><a href="/blog/2020-12-28-03-script元素.html" title="03-script元素"><img class="cover" src="/blog/img/hbs.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">03-script元素</div></div></a></div><div><a href="/blog/2020-12-28-02-实现.html" title="02-实现"><img class="cover" src="/blog/img/hbs.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">02-实现</div></div></a></div><div><a href="/blog/2020-12-28-04-文档模式.html" title="04-文档模式"><img class="cover" src="/blog/img/hbs.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">04-文档模式</div></div></a></div><div><a href="/blog/2020-12-28-05-语法.html" title="05-语法"><img class="cover" src="/blog/img/hbs.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">05-语法</div></div></a></div><div><a href="/blog/2020-12-28-06-变量声明.html" title="06-变量声明"><img class="cover" src="/blog/img/hbs.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-12-28</div><div class="title">06-变量声明</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/blog/img/lufei_siwangningshi.jpg" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">BluesYoung-web</div><div class="author-info__description">一枚不善言辞的技术宅</div></div><div class="card-info-data is-center"><div class="card-info-data-item"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">153</div></a></div><div class="card-info-data-item"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">54</div></a></div><div class="card-info-data-item"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">48</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://gitee.com/BluesYoung-web"><i class="fab fa-gitee"></i><span>点个小星星吧</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/BluesYoung-web" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:15171255945@163.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a></div></div><div class="sticky_layout"><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/blog/2021-08-24-%E7%A7%BB%E5%8A%A8%E7%AB%AF%E8%BD%AF%E9%94%AE%E7%9B%98%E5%AF%BC%E8%87%B4%E5%B8%83%E5%B1%80%E9%94%99%E4%B9%B1.html" title="移动端软键盘导致布局错乱"><img src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/img/default.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="移动端软键盘导致布局错乱"/></a><div class="content"><a class="title" href="/blog/2021-08-24-%E7%A7%BB%E5%8A%A8%E7%AB%AF%E8%BD%AF%E9%94%AE%E7%9B%98%E5%AF%BC%E8%87%B4%E5%B8%83%E5%B1%80%E9%94%99%E4%B9%B1.html" title="移动端软键盘导致布局错乱">移动端软键盘导致布局错乱</a><time datetime="2021-08-24T10:01:20.000Z" title="发表于 2021-08-24 18:01:20">2021-08-24</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021-08-16-Linux%E5%AE%89%E8%A3%85you-get.html" title="Linux安装you-get"><img src="/blog/img/shumeipai_cover.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="Linux安装you-get"/></a><div class="content"><a class="title" href="/blog/2021-08-16-Linux%E5%AE%89%E8%A3%85you-get.html" title="Linux安装you-get">Linux安装you-get</a><time datetime="2021-08-16T08:07:31.000Z" title="发表于 2021-08-16 16:07:31">2021-08-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021-08-16-git%E5%88%A0%E9%99%A4%E8%BF%9C%E7%A8%8B%E4%BB%93%E5%BA%93%E7%9A%84%E6%8F%90%E4%BA%A4.html" title="git删除远程仓库的提交"><img src="/blog/img/skill.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="git删除远程仓库的提交"/></a><div class="content"><a class="title" href="/blog/2021-08-16-git%E5%88%A0%E9%99%A4%E8%BF%9C%E7%A8%8B%E4%BB%93%E5%BA%93%E7%9A%84%E6%8F%90%E4%BA%A4.html" title="git删除远程仓库的提交">git删除远程仓库的提交</a><time datetime="2021-08-16T07:52:02.000Z" title="发表于 2021-08-16 15:52:02">2021-08-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021-08-13-%E5%B0%86pad%E6%89%A9%E5%B1%95%E4%B8%BA%E7%94%B5%E8%84%91%E7%9A%84%E5%89%AF%E5%B1%8F.html" title="将pad扩展为电脑的副屏"><img src="/blog/img/skill.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="将pad扩展为电脑的副屏"/></a><div class="content"><a class="title" href="/blog/2021-08-13-%E5%B0%86pad%E6%89%A9%E5%B1%95%E4%B8%BA%E7%94%B5%E8%84%91%E7%9A%84%E5%89%AF%E5%B1%8F.html" title="将pad扩展为电脑的副屏">将pad扩展为电脑的副屏</a><time datetime="2021-08-13T11:44:04.000Z" title="发表于 2021-08-13 19:44:04">2021-08-13</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021-08-11-Linux%E5%90%AF%E7%94%A8SSH%E6%9C%8D%E5%8A%A1.html" title="Linux启用SSH服务"><img src="/blog/img/shumeipai_cover.jpg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="Linux启用SSH服务"/></a><div class="content"><a class="title" href="/blog/2021-08-11-Linux%E5%90%AF%E7%94%A8SSH%E6%9C%8D%E5%8A%A1.html" title="Linux启用SSH服务">Linux启用SSH服务</a><time datetime="2021-08-11T10:50:04.000Z" title="发表于 2021-08-11 18:50:04">2021-08-11</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2021 By BluesYoung-web</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/blog/js/utils.js"></script><script src="/blog/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script src="/blog/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>if (document.getElementsByClassName('mermaid').length) {
  if (window.mermaidJsLoad) mermaid.init()
  else {
    getScript('https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js').then(() => {
      window.mermaidJsLoad = true
      mermaid.initialize({
        theme: 'default',
      })
      false && mermaid.init()
    })
  }
}</script></div><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script> <script src="/blog/js/xkTool.js"></script> <script src="/blog/js/mySelf.js"></script><canvas class="fireworks" mobile="false"></canvas><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/fireworks.min.js"></script><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-nest.min.js"></script></div></body></html>